<template>
    <div style="background-color: #fff;margin: 8px;padding: 20px;height: 100%;text-align: left;">
        <div>
            <h1 class="title">音色 - {{ voiceInfo?.alias }}</h1>
        </div>
        <div>
            <div style="height: 100%;">
                <div>
                    <el-form label-position="top">
                        <el-form-item label="音色名称">
                            <el-input placeholder="请输入音色名称。" v-model="voiceInfo.alias" class="input-with-select">
                                <template #append>
                                    <el-button type="primary" @click="updateVoice">
                                        <el-icon :size="12">
                                            <Edit />
                                        </el-icon>编辑</el-button>
                                </template>
                            </el-input>
                        </el-form-item>

                        <el-form-item label="待合成文本">
                            <el-input type="textarea" rows="4" placeholder="请输入待合成的文本。" v-model="ttsForm.text" />
                        </el-form-item>
                        <el-form-item label="">
                            <el-button style="width: 100%;" type="primary" @click="synthesizeVoice"
                                :disabled="isSynthesizing">提交合成</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div>
                <el-card style="height: 100%;" shadow="never">
                    <div v-if="audioUrl">
                        <div>
                            <h3 class="title">语音克隆结果</h3>
                        </div>
                        <audio controls :key="audioKey" style="width: 100%;">
                            <source :src="audioUrlWithTimestamp" type="audio/wav">
                            您的浏览器不支持 audio 元素。
                        </audio>
                    </div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            id: 0,
            inputDisabled: false,
            form: {
                fileList: []
            },
            voiceInfo: { id: "", character_id: "", location: "", name: "", introduction: "", voice_id: "", role_agent_id: null, memory: "", history: [] },
            imgBaseURL: import.meta.env.VITE_DOWNFILE_API_BASE_URL,
            VITE_UPLOAD_API_BASE_URL: import.meta.env.VITE_UPLOAD_API_BASE_URL,
            roleAgentList: [],
            ttsForm: {
                text: ""
            },
            audioUrl: "",
            audioKey: 0, // 添加一个 key 来控制 audio 元素的重新渲染
            isSynthesizing: false // 添加一个标志来控制按钮的禁用状态
        }
    },
    computed: {
        audioUrlWithTimestamp() {
            if (this.audioUrl) {
                const timestamp = new Date().getTime();
                return `${this.audioUrl}?t=${timestamp}`;
            }
            return "";
        }
    },
    methods: {
        async getVoiceInfo() {
            try {
                const response = await fetch(`${import.meta.env.VITE_API_URL}/voiceBank/getVoiceInfo`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id: this.id })
                });
                if (response.status === 401) {
                    localStorage.removeItem('access_token');
                    this.$router.push('/login');
                    return;
                }
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const rs = await response.json();
                console.log("rs:>>:", rs);
                this.voiceInfo = rs.data;
            } catch (error) {
                console.error('There was a problem with the fetch operation:', error);
            }
        },
        async updateVoice() {
            try {
                const response = await fetch(`${import.meta.env.VITE_API_URL}/voiceBank/updateVoice`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.voiceInfo)
                });
                if (response.status === 401) {
                    localStorage.removeItem('access_token');
                    this.$router.push('/login');
                    return;
                }
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const rs = await response.json();
                console.log("rs:>>:", rs);
                this.getVoiceInfo();
            } catch (error) {
                console.error('There was a problem with the fetch operation:', error);
            }
        },
        async synthesizeVoice() {
            if (!this.ttsForm.text || !this.voiceInfo.name) {
                this.$message.warning('请填写所有必填项');
                return;
            }

            this.isSynthesizing = true; // 禁用按钮

            try {
                const response = await fetch(`${import.meta.env.VITE_API_URL}/voiceBank/tts`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        text: this.ttsForm.text,
                        voice_name: this.voiceInfo.name
                    })
                });

                if (response.status === 401) {
                    localStorage.removeItem('access_token');
                    this.$router.push('/login');
                    return;
                }
                if (response.ok) {
                    const responseData = await response.json();
                    if (responseData.code === 200) {
                        this.audioUrl = responseData.data.audio_url;
                        this.audioKey += 1; // 增加 key 以强制重新渲染 audio 元素
                    } else {
                        this.$message.error("合成失败: " + JSON.stringify(responseData));
                    }
                } else {
                    this.$message.error("网络请求失败");
                }
            } catch (error) {
                console.error(error);
                this.$message.error("发生错误: " + error.message);
            } finally {
                this.isSynthesizing = false; // 启用按钮
            }
        }
    },
    mounted() {
        this.id = this.$route.params.id || 0;
        console.log(this.id);
        this.getVoiceInfo();
    }
}
</script>

<style>
.el-card__body {
    height: 100% !important;
}
</style>
